
function prepareItemData_PreMod() {
	for (var oi=0; oi<modctx.itemdata.length; oi++) {
		var o = modctx.itemdata[oi];
		
		//may be changed in mod. need it to load description
		o.originalname = o.name;
	}		
}

function prepareItemData_PostMod() {
	var pathkeyorder = ['F', 'A', 'W', 'E', 'S', 'D', 'N', 'B', 'H']; 
	//{ A:'Air', B:'Blood', D:'Death', E:'Earth', F:'Fire', N:'Nature', S:'Astral', W:'Water', H:'Holy' };
	var forgeCost = { 1:5, 2:10, 3:15, 4:25, 5:40, 6:65, 7:90, 8:115, 9:140 };

	for (var oi=0; oi<modctx.itemdata.length; oi++) {
		var o = modctx.itemdata[oi];
		
		//convert to numbers (for column ordering)
		//doesn't seem to cause any further problems..
		o.id = parseInt(o.id);
		o.con = parseInt(o.con);
		
		//serachable string
		o.searchable = ' ' + o.id + ' ' + o.name.toLowerCase();
		
		//sprite
		if (o.copyspr && modctx.itemlookup[o.copyspr])
			o.copyspr = modctx.itemlookup[o.copyspr].id;
		else o.copyspr = o.id;
		
		//combine linked armor stats
		if (o.armor) {
			var a = o.armor = modctx.armorlookup[o.armor];
			
			if (o.type=="shield") {
				o.protshield = a.prot;
				o.parry = a.def;
				o.def = addStringNumbers(o.def, '-'+a.enc);
			}
			else {
				if (o.type=="helm")
					o.prothead = a.prot;
				else
					o.prot = a.prot;

				o.def = addStringNumbers(o.def, a.def);//, '-'+a.enc);
			}
			o.enc = a.enc;
		}
		
		//clear lv2 if p2 was removed
		if (o.p2=='') o.lv2 = '';
		
		//path: E1D1
		o.mpath = o.p1 + o.lv1 + (o.p2 || "") + (o.lv2 || "");
		
		//gemcost: 5E5D
		o.gemcost = forgeCost[o.lv1] + o.p1 + (forgeCost[o.lv2] || "") + (o.p2 || ""); 
		
		//booster +DDD
		o.boosters = "";
		for (var i=0; i<pathkeyorder.length; i++) {
			var p = pathkeyorder[i];
			for (var j=0; j<parseInt(o[p]); j++) 
				o.boosters += p;
		}
		//set weapon class (ranged or melee)
		if (o.type == '1-h wpn' || o.type == '2-h wpn') {
			wpn = modctx.wpnlookup[o.wpn];
			if (wpn && wpn.shots && wpn.shots != '0')
				o.wpnclass = 'missile';
			else 
				o.wpnclass = 'melee';
		}
		
			
		if (o.boosters)
			o.boosters = '+'+o.boosters;
	}
}


function boosterFormatter(row, cell, value, columnDef, dataContext) {
	return pathFormatter(0,0, value.replace(/\d/,'+') );
}
function itemConFormatter(row, cell, value, columnDef, dataContext) {
	if (value==12) return 'Unforgeable';
	return "Constr " + value;
}


var ItemGrid = Class( D3MIGrid, function() {
	//grid columns
	$('#item-page .grid-container').css('width', 530);
	var columns = [
		{ id: "name",     width: 145, name: "Item Name", field: "name", sortable: true },
		{ id: "type",     width: 60, name: "Type", field: "type", sortable: true },
		{ id: "con",      width: 70, name: "Research", field: "con", sortable: true, formatter: itemConFormatter },
		{ id: "mpath",    width: 70, name: "Magic Req", field: "mpath", sortable: true, formatter: pathFormatter },
		{ id: "boosters", width: 165, name: "Boosters", field: "boosters", sortable: true, formatter: boosterFormatter }
	];
	this.superClass.call(this, '#item-page', modctx.itemdata, columns); //superconstructor

	//closure scope
	var that = this;
	
	//renders details boxes
	//this.renderOverlay = renderItemDetails;

	//wire up search boxes
	$("#item-page .search-box").bind('change keyup', function(e) { that.doSearch(); });
	$("#item-page .toggle-path").bind('change click', function(e) { that.doSearch(); });
	$("#item-page .select-type").bind('change', function(e) { that.doSearch(); });
	$("#item-page .select-con").bind('change', function(e) { that.doSearch(); });
	$("#item-page .clear-search-box").click(function(e) {
			$("#item-page .search-box").val('');
			$("#item-page .toggle-path").removeAttr("checked");
			$("#item-page .select-type option:first").attr('selected', true);
			$("#item-page .select-con option:first").attr('selected', true);
			that.doSearch();
	});
		
	//reads search boxes
	this.getSearchArgs = function(domsel) {
		var args = {
			str: $(domsel+" .search-box").val(),
			mpaths: '',
			type: $(domsel+" .select-type").val(),
			con: parseInt( $(domsel+" .select-con").val() )
		};
		//create string of mpaths from checkboxes
		$('#item-page .toggle-path:checked').each(function() {
			args.mpaths += this.name;
		});
		return args;
	}
	//apply search
	this.searchFilter =  function(o, args) {
		//check construction level
		if (args.con==12 && o.con!=12)
			return false;
		if (o.con > args.con)
			return false;

		//search string
		if (args.str && o.searchable.indexOf(args.str) == -1)
			return false;
		
		//magic paths
		if (args.mpaths) {
			if (args.mpaths.indexOf(o.p1) == -1)
				return false;
			if (o.p2 && args.mpaths.indexOf(o.p2) == -1)
				return false;
		}
		
		//item type
		if (args.type == 'melee' || args.type == 'missile') {
			if (o.wpnclass != args.type) 
				return false;
		} 
		else if (args.type && args.type.indexOf(o.type) == -1) {
			return false;
		}
		
		return true;
	}

	//customise sort	
	this.preSort = function(){
		//bound scope
		var boosterSortPriority = ['F', 'A', 'W', 'E', 'S', 'D', 'N', 'B', 'H'];
		var isSortedOnBoosters = false;
		var data = modctx.itemdata;
			
		//the actual callback
		return function(e, args) {
			if (args.sortCol.field == 'boosters') {
				//rotate booster priority 
				// if (isSortedOnBoosters)
				// 	boosterSortPriority.unshift(boosterSortPriority.pop());
				
				// var L = boosterSortPriority[0];
				
				// //pull priority to front of booster strings
				// var regex = new RegExp('^.([^'+L+']*)('+L+'+)([^'+L+']*)$');
				// for (var i=0; i<data.length; i++) {
				// 	var b = data[i].boosters;
				// 	if (b && b.indexOf(L)!=-1)
				// 		data[i].boosters = b.replace(regex, "_$2$1$3");
				// 	else if (b)
				// 		data[i].boosters = b.replace('_','+');
				// }
				if (isSortedOnBoosters) {
					//rotate priority 
					var pL = boosterSortPriority[0];
					boosterSortPriority.push(boosterSortPriority.shift());
					
					//push last priority to end
					var regex = new RegExp('^.('+pL+'+)(.*)$');
					for (var i=0; i<data.length; i++) {
						var b = data[i].boosters;
						if (b && b.indexOf(pL)!=-1)
							data[i].boosters = b.replace(regex, "+$2$1");
					}
				}
				var L = boosterSortPriority[0];
				
				//set first character to number of instances of L
				for (var i=0; i<data.length; i++) {
					var b = data[i].boosters;
					if (b && b.indexOf(L)!=-1)
						data[i].boosters =  String(b.split(L).length-1) + b.substr(1);
				}
				//switch sort column header icon
				if ( $('#itemboosterordericon')
				     .attr({alt:L, src:'images/magicicons/Path_'+L+'.png', 'class':'pathicon Path_'+L})
				     .css('visibility','visible')
				     .length==0 ) 
				{
					//add icon if not exists yet
					$(".slick-header-column[title=Boosters]")
					.append('<img id="itemboosterordericon" alt="'+L+'" class="pathicon Path_'+L+'" src="images/magicicons/Path_'+L+'.png" />')
					.find(".slick-sort-indicator").css('visibility','hidden');
				}
				//fix sort direction
				args.sortAsc = false;
				isSortedOnBoosters = true;
			} 
			else  {
				//hide sort column header icon if sorting another column
				$('#itemboosterordericon').css('visibility','hidden');
				isSortedOnBoosters = false;
			}
		}
		//exit bound scope
	}();

	//final init
	this.init();
});
